/**
 * 加签弹框
 */
import React, { Component } from "react";
import { connect } from "react-redux"
import {Modal, Form, Radio, Input, Spin, Select, message} from "antd";
import { messages } from "share/common";
import errorMessage from "share/errorMessage";
import Chooser from "components/chooser";
import VerifyControlModal from "./verify-control-modal";
import bagService from "../invoice-bag-approve.service";
import approveService from "../../../approve/approve.service";

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@Form.create()
@connect(mapStateToProps)
class ModalAddSign extends Component {

  userTypeStorage = `counterSign-userType_${this.props.entityType}`;

  sequenceStorage = `counterSign-sequence_${this.props.entityType}`;

  state = {
    loading: false,
    signUserLoading: false,
    signUserType: (this.props.info || {}).signUserType || +(localStorage.getItem(this.userTypeStorage) || 1001),
    auditSignUser: [],
    auditSignUserLoading: false,
    showCheckResult: false,
    checkResult: {},
  };

  componentDidMount() {
    const { info } = this.props;
    if (info && info.signUserType === 1002) {
      this.setState({ signUserLoading: true });
      this.getAuditSignUsers();
    }
  }

  getAuditSignUsers = () => {
    const { entityId, entityType } = this.props;
    if (this.state.auditSignUser.length) return
    this.setState({ auditSignUserLoading: true });
    bagService.getAuditSignList(entityId, entityType)
      .then(res => this.setState({ auditSignUser: res.data || [] }))
      .finally(() => this.setState({ auditSignUserLoading: false, signUserLoading: false }))
  };

  handleChangeType = e => {
    this.props.form.setFieldsValue({ person: undefined });
    this.setState({ signUserType: e.target.value });
    localStorage.setItem(this.userTypeStorage, e.target.value);
  };

  handleSubmit = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.props.entityType === 5001) {
          this.counterSignBag(values);
        } else {
          this.counterSignBill(values);
        }
      }
    })
  };

  // 单据加签
  counterSignBill = values => {
    const { auditSignUser } = this.state;
    const { loginUser, entityOID, entityType } = this.props;
    const { person, approvalTxt, sequence, signUserType } = values;
    // 向前加签
    if (sequence === 'forward') {
      const params = {
        entities: [{
          entityOID,
          entityType,
          signUserType,
          countersignApproverOIDs: signUserType === 1001 ? person.map(item => item.userOID) : [person],
          approverOID: loginUser.userOID
        }],
        approvalTxt
      };
      this.setState({ loading: true });
      approveService.postForwardAdditional(params)
        .then(res => {
          if (res.data.failNum === 0) {
            message.success(messages('expense-15.key2')/*加签成功*/);
            this.props.close(true);
          } else {
            message.error(`${messages('common.operate.filed')/*操作失败*/}，${res.data.failReason[entityOID]}`)
          }
        })
        .catch(e => errorMessage(e.response))
        .finally(() => this.setState({ loading: false }));
    }
    // 向后加签
    if (sequence === 'backward') {
      values.result = signUserType === 1001 ? person :
        [{ fullName: auditSignUser.filter(item => item.userOID === person)[0].fullName, userOID: person }]
      this.props.onBackSign(values);
    }
  };

  // 发票袋加签
  counterSignBag = values => {
    const { auditSignUser } = this.state;
    const { entityId } = this.props;
    const { person, approvalTxt, sequence, signUserType } = values;
    // 向前加签
    if (sequence === 'forward') {
      const params = {
        bagId: entityId,
        countersignOIDs: signUserType === 1001 ? person.map(item => item.userOID) : [person],
        signUserType,
        approvalTxt
      };
      this.setState({ loading: true });
      bagService.bagCounterSign(params)
        .then(res => {
          if (res.data.failNum === 0) {
            message.success(messages('expense-15.key2')/*加签成功*/);
            this.props.close(true);
          } else {
            this.setState({
              showCheckResult: true,
              checkResult: res.data || {}
            });
          }
        })
        .catch(e => {
          errorMessage(e.response)
        })
        .finally(() => this.setState({ loading: false }));
    }
    // 向后加签
    if (sequence === 'backward') {
      values.result = signUserType === 1001 ? person :
        [{ fullName: auditSignUser.filter(item => item.userOID === person)[0].fullName, userOID: person }]
      this.props.onBackSign(values);
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible, entityId, entityType, signCompanyOIDs, signApprovalIsEmpty, info = {} } = this.props;
    const {
      loading, signUserType, auditSignUser, auditSignUserLoading, showCheckResult, checkResult, signUserLoading
    } = this.state;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 16, offset: 1 }
    };
    const approveSignDisable = entityType === 5001 && signApprovalIsEmpty && signCompanyOIDs.length === 0;
    return (
      <Modal
        visible={visible}
        title={messages('expense-15.key3')/*加签*/}
        width={720}
        confirmLoading={loading}
        onOk={this.handleSubmit}
        onCancel={() => this.props.close()}
      >
        <Form>
          <FormItem
            {...formItemLayout}
            label={messages('expense-15.key4')/*加签人员类型*/}
            extra={(
              <div>
                {messages('expense-15.key5')/*“加签审批人”，可加签任意人在“审批”菜单处理单据*/} <br/>
                {messages('expense-15.key6')/*“加签审核人”，仅可加签审核过该单据的财务在“单据审核”菜单处理单据*/}
              </div>
            )}
          >
            {getFieldDecorator('signUserType', {
              rules: [{
                required: true
              }],
              initialValue: info.signUserType || +(localStorage.getItem(this.userTypeStorage) || 1001)
            })(
              <RadioGroup onChange={this.handleChangeType}>
                <Radio value={1001}>{messages('expense-15.key7')/*加签审批人*/}</Radio>
                <Radio value={1002}>{messages('expense-15.key8')/*加签审核人*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-15.key9')/*加签给*/}>
            {getFieldDecorator('person', {
              rules: [{
                required: true,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: info.result && info.result.length ?
                (signUserType === 1001 ? info.result : info.result[0].userOID) :
                undefined
            })(
              signUserLoading ? <Spin size="small"/> : signUserType === 1001 ? (
                <Chooser
                  type="user"
                  valueKey="userOID"
                  labelKey="fullName"
                  listExtraParams={signCompanyOIDs ? { //需要两个参数的原因见 bug 20966
                    corporationOID: signCompanyOIDs,
                    companyOID: signCompanyOIDs,
                    roleType: 'TENANT'
                  } : {
                    roleType: 'TENANT'
                  }}
                  newline
                  showDetail
                  disabled={approveSignDisable}
                  placeholder={approveSignDisable ?
                    messages('expense-15.key10')/*暂无审批人可加签*/ :
                    messages('common.select')/*请选择*/
                  }
                />
              ) : (
                <Select
                  placeholder={messages('common.select')/*请选择*/}
                  showSearch
                  allowClear
                  notFoundContent={auditSignUserLoading ? <Spin size="small" /> :
                    messages('expense-15.key11')/*暂无审核人可加签*/}
                  onFocus={this.getAuditSignUsers}
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {auditSignUser.map(item =>
                    <Option key={item.userOID}>{item.employeeID} - {item.fullName}</Option>
                  )}
                </Select>
              )
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-15.key12')/*加签顺序*/}>
            {getFieldDecorator('sequence', {
              initialValue: localStorage.getItem(this.sequenceStorage) || 'backward'
            })(
              <RadioGroup style={{ width: '100%' }} onChange={e => localStorage.setItem(this.sequenceStorage, e.target.value)}>
                <Radio value="backward" style={{ whiteSpace: 'normal' }}>
                  {messages('expense-15.key13')/*向后加签*/}&nbsp;
                  {messages('expense-15.key14')/*我审核通过后再由加签人处理*/}
                </Radio>
                <Radio value="forward" style={{ whiteSpace: 'normal' }}>
                  {messages('expense-15.key15')/*向前加签*/}&nbsp;
                  {messages('expense-15.key16')/*加签人通过后再由我审核*/}
                </Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-15.key17')/*加签意见*/}>
            {getFieldDecorator('approvalTxt', {
              rules: [{
                max: 500,
                message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
              }],
              initialValue: info.approvalTxt
            })(
              <TextArea
                rows={4}
                placeholder={messages('expense-15.key18')/*加签意见，最多输入500个字符*/}
                style={{ resize: 'none' }}
              />
            )}
          </FormItem>
        </Form>

        <VerifyControlModal
          visible={showCheckResult}
          checkResult={checkResult}
          onCancel={() => this.setState({ showCheckResult: false })}
        />
      </Modal>
    )
  }
}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
  }
}

export default ModalAddSign;
